package org.elcom.sources;

import java.io.IOException;
import java.net.ConnectException;
import java.util.TimerTask;

import org.apache.commons.net.ftp.FTPClient;

public class Connect extends TimerTask{
	
	static FTPClient ftpClient = new FTPClient();
	static boolean result = true;

	@Override
	public void run() {
		try {
			if (!ftpClient.isConnected()) {
				connectToServer();	
			}
			
			//download file from server
			FTPDownload.downloadDirectory(ftpClient, Config.remoteDirPath, "", Config.templateDir);

		} catch (Exception ex) {
			reconnectToServer(Config.waitingTime);
		}
	}

	public static void connectToServer() {
		// connect and login to the server
		try {
			ftpClient.connect(Config.ip, Config.port);
			result = ftpClient.login(Config.user, Config.pass);
			if(!ftpClient.isConnected()){
				System.out.println("Connect failed");
				reconnectToServer(Config.waitingTime);
			}
			else {
				System.out.println("Connected success");
			}
			// use local passive mode to pass firewall
			ftpClient.enterLocalPassiveMode();
			
			if(!result){
				System.out.println("Login failed, Check your user or password");
				reconnectToServer(Config.waitingTime);
			} else {
				System.out.println("Login success");
			}
		} catch (ConnectException e) {
			reconnectToServer(Config.waitingTime);
		} catch (IOException e) {
			System.out.println("Error");
		}
				
	}

	public static void reconnectToServer(final int ti){

		int waited = 0;
		System.out.println("Reconnecting...");
		while(waited < ti){
			
			try {
				ftpClient.connect(Config.ip, Config.port);
				result = ftpClient.login(Config.user, Config.pass);
			} catch (IOException e) {
				result = false;
			} catch (Exception e) {
				System.out.println("Error");
				e.printStackTrace();
			}
			if(ftpClient.isConnected() && result == true){
				System.out.println("Reconnected success");
				break;
			}else {
				waited += 1000;
			}
		}
		if(!result){
			System.out.println("Reconnect failed");	
		}
	}
}
